package com.tingyuge.base.thread.pool;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.IntStream;

/**
 * @author xiaodao
 * @version 1.0
 * @date 2021/2/27
 * 对于线程池来说,其提供了execute和submit 俩种方式来向线程池提交任务
 * sumbit可以取代execute方法,因为可以接受callable方法,也可以接受runable方法
 *
 * 关于线程池的总体执行策略
 * 1.如果线程池中 正在执行的线程 <corePoolSize,那么会优先创建新的线程来执行任务
 * 2.如果线程中,正在执行的线程数>=corePoolSize,那么线程池中会对提交的任务进行阻塞排队.而不是创建新的线程
 * 3.如果提交的任务无法加入到阻塞队列,线程就会创建新的线程,从阻塞队列中拉取任务来执行,如果创建的线程=maximumPoolSize,那么拒绝策略就会起作用.
 * 关于线程任务的提交.
 *  1.俩种提交方式,sumit和execute
 *  2.sumbit 有三种方式,无论哪种方式,最终都会将传递进行来的任务转换为一个Callable对象进行处理
 *  3.当callable对象构造完毕之后,最终都会调用executors.中的execute方法
 *
 *
 *
 *
 */
public class Test2Reject {
    public static void main(String[] args) throws InterruptedException {
     /*   ThreadPoolExecutor executor = new ThreadPoolExecutor(3,5, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<>(3),
                new ThreadPoolExecutor.AbortPolicy());*/
      /*  ThreadPoolExecutor executor = new ThreadPoolExecutor(3,5, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<>(3),
                new ThreadPoolExecutor.DiscardPolicy());*/
       /* ThreadPoolExecutor executor = new ThreadPoolExecutor(3,5, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<>(3),
                new ThreadPoolExecutor.DiscardOldestPolicy());*/
        ThreadPoolExecutor executor =ThreadPoolUtil.getInstance("test");
        List< Future<String>> futures = new ArrayList<>();
        IntStream.range(0,9).forEach(i->{
            Future<String> submit = executor.submit(() -> {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String result = i + "---" + Thread.currentThread().getName();
                System.out.println(result);
                return result;
            });
            futures.add(submit);
        });
        Thread.sleep(2000);
        System.out.println("------------------------");
        for (Future<String> future : futures) {
            try {
                    System.out.println("futrue: "+ future.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }

}
